package com.jieli.stream.dv.running2.ui.base;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.SupplicantState;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;

import com.jieli.stream.dv.running2.ui.MainApplication;
import com.jieli.stream.dv.running2.util.ActivityManager;
import com.jieli.stream.dv.running2.util.AppUtils;
import com.jieli.stream.dv.running2.util.Dbug;
import com.jieli.stream.dv.running2.util.IActions;
import com.jieli.stream.dv.running2.util.IConstant;
import com.jieli.stream.dv.running2.util.PreferencesHelper;
import com.jieli.stream.dv.running2.util.WifiHelper;

/**
 * Activity基类
 * date : 2017/02/27
 */
public abstract class BaseActivity extends FragmentActivity implements IConstant, IActions {
    private final String TAG = getClass().getSimpleName();
    public WifiHelper mWifiHelper;
    public MainApplication mApplication;
    private BaseWifiBroadcastReceiver mReceiver;

    /**
     * Wifi广播处理
     */
    private class BaseWifiBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent == null) return;
            SharedPreferences sharedPreferences;
            String action = intent.getAction();
            if(TextUtils.isEmpty(action)) return;
            switch (action) {
                case WifiManager.NETWORK_STATE_CHANGED_ACTION:
                    if (mWifiHelper == null) {
                        mWifiHelper = WifiHelper.getInstance(getApplicationContext());
                    }
                    NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                    WifiInfo wifiInfo = intent.getParcelableExtra(WifiManager.EXTRA_WIFI_INFO);
                    if (networkInfo == null) {
                        Dbug.e(TAG, "networkInfo is null");
                        mWifiHelper.notifyWifiError(ERROR_NETWORK_INFO_EMPTY);
                        return;
                    }
//                    Dbug.w(TAG, "networkInfo : " + networkInfo.toString());
                    boolean isWifiConnected = (networkInfo.getDetailedState() == NetworkInfo.DetailedState.CONNECTED);
                    if (isWifiConnected) {
                        if (networkInfo.getType() != ConnectivityManager.TYPE_WIFI) {
                            Dbug.e(TAG, "networkType is not TYPE_WIFI");
                            mWifiHelper.notifyWifiError(ERROR_NETWORK_TYPE_NOT_WIFI);
                            return;
                        }
                        if (wifiInfo == null || TextUtils.isEmpty(wifiInfo.getSSID())) {
                            Dbug.e(TAG, "wifiInfo is  empty or ssid is null");
                            mWifiHelper.notifyWifiError(ERROR_WIFI_INFO_EMPTY);
                            return;
                        }
//                        Dbug.i(TAG, "wifiInfo : " + wifiInfo.toString());
                        mWifiHelper.notifyWifiConnect(wifiInfo);
                        /*String preSsid = PreferencesHelper.getSharedPreferences(mApplication).getString(CURRENT_WIFI_SSID, "");
                        //防止已连接的情况下，不经手动点击就进入主界面
                        if (!TextUtils.isEmpty(preSsid)) mWifiHelper.notifyWifiConnect(wifiInfo);
                        else Dbug.i(TAG, "It has been try to connect device");*/
                    }
                    break;
                case WifiManager.SUPPLICANT_STATE_CHANGED_ACTION:
                    if (mWifiHelper == null) {
                        mWifiHelper = WifiHelper.getInstance(getApplicationContext());
                    }
                    SupplicantState state = intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
                    int supplicantError = intent.getIntExtra(WifiManager.EXTRA_SUPPLICANT_ERROR, -1);
                    Dbug.i(TAG, "supplicantError=" + supplicantError + ", state=" + state);
                    if (SupplicantState.DISCONNECTED.equals(state) && supplicantError == WifiManager.ERROR_AUTHENTICATING) {
                        mWifiHelper.notifyWifiError(ERROR_WIFI_PWD_NOT_MATCH);
                        sharedPreferences = PreferencesHelper.getSharedPreferences(getApplicationContext());
                        String cSSID = sharedPreferences.getString(CURRENT_WIFI_SSID, null);
                        if (!TextUtils.isEmpty(cSSID)) {
                            mWifiHelper.removeSavedNetWork(cSSID);
                            PreferencesHelper.remove(getApplicationContext(), cSSID);
                            PreferencesHelper.remove(getApplicationContext(), CURRENT_WIFI_SSID);
                        }
                    }
                    break;
                case ConnectivityManager.CONNECTIVITY_ACTION:
                    if (mWifiHelper == null) {
                        mWifiHelper = WifiHelper.getInstance(getApplicationContext());
                    }
                    if (!mWifiHelper.isWifiOpen()) {
                        int wifiState;
                        if (WifiHelper.isNetWorkConnectedType(getApplicationContext(), ConnectivityManager.TYPE_MOBILE)) {
                            wifiState = ERROR_NETWORK_TYPE_NOT_WIFI;
                        } else {
                            wifiState = ERROR_NETWORK_NOT_OPEN;
                        }
                        mWifiHelper.notifyWifiError(wifiState);
                    } else {
                        ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                        NetworkInfo netInfo = null;
                        if (conMan != null) {
                            netInfo = conMan.getActiveNetworkInfo();
                        }
                        if (netInfo != null && netInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                            WifiInfo info = mWifiHelper.getWifiConnectionInfo();
                            if (info == null) return;
                            Dbug.i(TAG, "Have Wifi Connection:" +info.getSSID());
                            mWifiHelper.notifyWifiConnect(info);
                            /*String preSsid = PreferencesHelper.getSharedPreferences(mApplication).getString(CURRENT_WIFI_SSID, "");
                            //防止已连接的情况下，不经手动点击就进入主界面
                            if (!TextUtils.isEmpty(preSsid)) mWifiHelper.notifyWifiConnect(info);
                            else Dbug.i(TAG, "It has been try to connect device");*/
                        } else Dbug.e(TAG, "Don't have Wifi Connection");
                    }
                    break;
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mApplication = MainApplication.getApplication();
        mWifiHelper = WifiHelper.getInstance(mApplication);
        ActivityManager.getInstance().pushActivity(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        registerBroadCastReceiver();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mReceiver != null) {
            MainApplication.getApplication().unregisterReceiver(mReceiver);
            mReceiver = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityManager.getInstance().popActivity(this);
    }

    private void registerBroadCastReceiver() {
        if (mReceiver == null) {
            mReceiver = new BaseWifiBroadcastReceiver();
        }
        IntentFilter baseFilter = new IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION); //Wifi 网络状态改变广播
        baseFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);                    //Wifi 认证状态广播
        baseFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);                        //网络改变广播
        MainApplication.getApplication().registerReceiver(mReceiver, baseFilter);
    }

    @Override
    protected void attachBaseContext(Context base) {
        String lan = PreferencesHelper.getSharedPreferences(MainApplication.getApplication()).getString(KEY_APP_LANGUAGE_CODE, "-1");
        super.attachBaseContext(AppUtils.changeAppLanguage(base, lan));
    }
    /*
     * ====================================== command api ========================================
     */
    /**
     * 切换fragment
     *
     * @param containerId layout id
     * @param fragment    fragment
     * @param fragmentTag fragment tag
     */
    public void changeFragment(int containerId, Fragment fragment, String fragmentTag) {
        if (fragment != null && !isFinishing() && !isDestroyed()) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            if (fragmentManager != null) {
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                if (fragmentTransaction != null) {
                    if (!TextUtils.isEmpty(fragmentTag)) {
                        fragmentTransaction.replace(containerId, fragment, fragmentTag);
                    } else {
                        fragmentTransaction.replace(containerId, fragment);
                    }
                    fragmentTransaction.addToBackStack(null);
                    fragmentTransaction.commitAllowingStateLoss();
                }
            }
        }
    }

    public void changeFragment(int containerId, Fragment fragment) {
        changeFragment(containerId, fragment, null);
    }

}
